package querysrc;
import javax.servlet.ServletException;
import java.sql.Connection;

import java.sql.SQLException;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;


public class sqlConnectionHandler { 
	
	 InitialContext ctx = null;
	 DataSource ds = null;	
	 
	 public Connection connect() throws ServletException
	 {
		Connection conn = null;
		boolean bret = true;
		try {
				bret = this.getDataSource();	
				if(bret)
				{
				    conn = ds.getConnection();
				    return conn;
				}
				else
					return null;
		    }
		    catch (SQLException se) {
		      System.out.println("SQLException: "+se.getMessage());
		      return null;
		    }	      
	 }
	 
	 public boolean getDataSource() throws ServletException
	 {
		 try {
			 synchronized (this)
			 {
				 if(ctx == null)
				 {				 
					 ctx = new InitialContext();
					 ds = (DataSource) ctx.lookup(serverInfo.jdni_name);
				 }
			 
				 else 
				 {
					 if(ds == null)
					 {
						 ds = (DataSource) ctx.lookup(serverInfo.jdni_name);
					
					 }
				 }
			 }
		     return true;
		    }		    
		    catch (NamingException ne) {
		      System.out.println("NamingException: "+ne.getMessage());
		      return false;
		    }
	 }
	 
	 public void finalize()
	 {
		 try {
			 synchronized (this)
			 {      
		      if (ctx != null)
		        ctx.close();
			 }
		    }    
		    catch (NamingException ne) {
		      System.out.println("NamingException: "+ne.getMessage());  
		    }  
	 }
	 
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
